package com.tpp.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tpp.admin.mapper.MenuMapper;
import com.tpp.admin.service.MenuService;
import com.tpp.admin.vo.MenuVo;
import com.tpp.comm.pojo.TpMenu;
import com.tpp.comm.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    private List<MenuVo> listToTree(Integer pre,List<TpMenu> menus){
        List<TpMenu> child = new ArrayList<>();
        for (TpMenu menu : menus) {
            if(pre.equals(menu.getParentId())){
                child.add(menu);
            }
        }
        List<MenuVo> result = new ArrayList<>();
        for (TpMenu tpMenu : child) {
            MenuVo menuVo = new MenuVo();
            BeanUtils.copyProperties(tpMenu,menuVo);
            menuVo.setChildren(listToTree(tpMenu.getId(),menus));
            result.add(menuVo);
        }
        return result;
    }

    @Override
    public List<MenuVo> queryMenuTree() {
        List<TpMenu> tpMenus = menuMapper.selectList(new QueryWrapper<TpMenu>().lambda().orderByAsc(TpMenu::getSort));
        List<MenuVo> menuVos = listToTree(0, tpMenus);
        return menuVos;
    }

    @Override
    public List<TpMenu> queryMenu() {
        return menuMapper.selectList(new QueryWrapper<TpMenu>().lambda().orderByAsc(TpMenu::getId));
    }

    @Override
    public void save(TpMenu tpMenu) {
        tpMenu.setCreatedTime(LocalDateTime.now());
        menuMapper.insert(tpMenu);
    }

    @Override
    public void update(TpMenu tpMenu) {
        tpMenu.setUpdatedTime(LocalDateTime.now());
        menuMapper.updateById(tpMenu);
    }

    @Override
    public void delete(Integer id) {
        menuMapper.deleteById(id);
    }

    @Override
    public TpMenu queryById(Integer id) {
        return menuMapper.selectById(id);
    }
}
